package com.dendi.controller;

import com.dendi.config.MyConfig;
import com.dendi.service.UserService;
import com.dendi.util.*;
import com.github.wxpay.sdk.WXPay;
import com.sun.org.apache.xpath.internal.SourceTree;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.jdom2.JDOMException;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;


@Controller
public class PayController2 {
    private static String ticketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=";

    @RequestMapping( "/toPay2")
    public String toPay(HttpServletRequest request,ModelMap model) throws Exception {
        System.out.println(1111111111);
        String code=request.getParameter("code");
        System.out.println("code ======="+code);
        String openId=WeiChatUtil.getOpenId(code);
        System.out.println("openId ======="+openId);
        request.getSession().setAttribute("openid",openId);
        return "prepay2";
    }

    @RequestMapping( "/pay2")
    public @ResponseBody String pay2(HttpServletRequest request,  String commodityName, double totalPrice,String clientUrl) throws Exception {
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/";
        System.out.println("clientUrl "+clientUrl);
        String spbill_create_ip = request.getRemoteAddr();
        spbill_create_ip = spbill_create_ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : spbill_create_ip;
        String tradeNo=request.getParameter("WIDout_trade_no");
        tradeNo=String.valueOf(new Date().getTime());
        MyConfig config = new MyConfig();
        WXPay wxpay = new WXPay(config);
        System.out.println("tradeNo "+tradeNo);
        Map<String, String> data = new HashMap<String, String>();
        data.put("body", "dishuihu");
        data.put("out_trade_no", tradeNo);
        data.put("device_info", "");
        data.put("fee_type", "CNY");
        data.put("total_fee", "2");
        data.put("spbill_create_ip", spbill_create_ip);
        data.put("notify_url", "http://www.icymi.cn/wechat/notice2");
        data.put("trade_type", "JSAPI");
        data.put("product_id", "12");
        String openid=request.getSession().getAttribute("openid").toString();
        System.out.println("openid  111111"+openid);
        data.put("openid",openid);

        try {
            Map<String, String> resp = wxpay.unifiedOrder(data);
            System.out.println("response======="+resp);



            String prepay_id=resp.get("prepay_id");

            SortedMap<String, String> finalpackage = new TreeMap<String, String>();
            String timestamp = Sha1Util.getTimeStamp();
            String nonce_str = UUID.randomUUID().toString().replaceAll("-", "");
            String packages = "prepay_id=" + prepay_id;
            // finalpackage.put("appId", WeiChatConfig.appid);
            finalpackage.put("timestamp", timestamp);
            finalpackage.put("noncestr", nonce_str);
            String ticket = WeiChatUtil.getjsApiTicket(ticketUrl, WeiChatUtil.getAccessToken());
            finalpackage.put("jsapi_ticket", ticket);
            finalpackage.put("url", clientUrl);
            // finalpackage.put("package", packages);
            // finalpackage.put("signType", WeiChatConfig.signType);
            String signature = Sha1Util.createSHA1Sign(finalpackage);
            System.out.println("signature 1111"+signature);
            //     jsjdk-signature end//
            SortedMap<String, String> finalpackage2 = new TreeMap<String, String>();
            finalpackage2.put("appId", WeiChatConfig.appid);
            finalpackage2.put("timeStamp", timestamp);
            finalpackage2.put("nonceStr", nonce_str);
            finalpackage2.put("package", packages);
            finalpackage2.put("signType", "MD5");
            String paySign = createSign(finalpackage2);
            /////paySign  end///
            SortedMap<Object, Object> result = new TreeMap<Object, Object>();
            result.put("appid", WeiChatConfig.appid);
            result.put("package", packages);
            result.put("packageValue", packages);
            result.put("paySign", paySign);
            result.put("bizOrderId", tradeNo);
            result.put("orderId", tradeNo);
            result.put("payPrice", 2 + "");
            result.put("signType", "MD5");
            result.put("sendUrl", basePath + "paysuccess2?totalPrice=2");
            System.out.println( "aaaaaaaaaaaaaaaaaaaaaaa"+basePath + "paysuccess2?totalPrice=2");
            result.put("config_nonceStr", nonce_str);
            result.put("config_timestamp", timestamp);
            result.put("config_sign", signature);
            String json = JSONArray.fromObject(result).toString();
            System.out.println("用于wx.config配置的json：" + json);
            return json;





        } catch (Exception e) {
            e.printStackTrace();
        }

		/*System.out.println("获取的预支付订单是：" + prepayid);
		if (prepayid != null && prepayid.length() > 10) {
			// 生成微信支付参数，此处拼接为完整的JSON格式，符合支付调起传入格式
			String jsParam = WXPay.createPackageValue(pay.getAppId(), pay.getPartnerKey(), prepayid);
			System.out.println("jsParam=" + jsParam);
			// 此处可以添加订单的处理逻辑
			model.addAttribute("jsParam", jsParam);
			logger.info("生成的微信调起JS参数为：" + jsParam);
		}
		model.addAttribute("prepayid", prepayid);*/

        return "prepay2";
    }

    @RequestMapping("/notice2")
    public void notice2(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("notice=======");
        PrintWriter out = response.getWriter();
        InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        outSteam.close();
        inStream.close();
        String result = new String(outSteam.toByteArray(), "utf-8");
        Map<String, String> map = null;
        try {
            map = XMLUtil.doXMLParse(result);
            System.out.println("notice map="+map);
        } catch (JDOMException e) {
            e.printStackTrace();
        }

        // 此处获取accessToken

        String accessToken = "3oWof69djPQPm2SWHrLmpDpmpMWMFYgxE4UKCc0QwEIt7MhdITnCOCdKxo6Df2LxAXkPRIsoDtyAqAGaQEDWlIKkqseoy5dA8VjOlul6UMs";
        // 此处调用订单查询接口验证是否交易成功

        //boolean isSucc = reqOrderquery(map, accessToken);
        boolean isSucc = true;
        // 支付成功，商户处理后同步返回给微信参数

        if (!isSucc) {
            // 支付失败

            System.out.println("支付失败");
        } else {
            System.out.println("===============付款成功==============");
            // ------------------------------

            // 处理业务开始

            // ------------------------------

            // 此处处理订单状态，结合自己的订单数据完成订单状态的更新

            // ------------------------------

            // 处理业务完毕

            // ------------------------------

            String noticeStr = setXML("SUCCESS", "");
            out.print(new ByteArrayInputStream(noticeStr.getBytes(Charset.forName("UTF-8"))));
        }
    }

    public static String setXML(String return_code, String return_msg) {
        return "<xml><return_code><![CDATA[" + return_code + "]]></return_code><return_msg><![CDATA[" + return_msg + "]]></return_msg></xml>";
    }

//	public static boolean reqOrderquery(Map<String, String> map, String accessToken) {
//		WXOrderQuery orderQuery = new WXOrderQuery();
//		orderQuery.setAppid(map.get("appid"));
//		orderQuery.setMch_id(map.get("mch_id"));
//		orderQuery.setTransaction_id(map.get("transaction_id"));
//		orderQuery.setOut_trade_no(map.get("out_trade_no"));
//		orderQuery.setNonce_str(map.get("nonce_str"));
//
//		//此处需要密钥PartnerKey，此处直接写死，自己的业务需要从持久化中获取此密钥，否则会报签名错误
//		orderQuery.setPartnerKey("c9f09543c97719849d51286905261d76");
//
//		Map<String, String> orderMap = orderQuery.reqOrderquery();
//		//此处添加支付成功后，支付金额和实际订单金额是否等价，防止钓鱼
//		if (orderMap.get("return_code") != null && orderMap.get("return_code").equalsIgnoreCase("SUCCESS")) {
//			if (orderMap.get("trade_state") != null && orderMap.get("trade_state").equalsIgnoreCase("SUCCESS")) {
//				String total_fee = map.get("total_fee");
//				String order_total_fee = map.get("total_fee");
//				if (Integer.parseInt(order_total_fee) >= Integer.parseInt(total_fee)) {
//					return true;
//				}
//			}
//		}
//		return false;
//	}

    public String createSign(SortedMap<String, String> packageParams) {
        StringBuffer sb = new StringBuffer();
        Set es = packageParams.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k)
                    && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=wanganyimihongyangcuiwenteng1234" );
        String sign = MD5Util.MD5Encode(sb.toString(), "UTF-8")
                .toUpperCase();
        System.out.println("packge签名="+sign);
        return sign;

    }

    @RequestMapping("paysuccess2")
    public ModelAndView paysuccess2(HttpServletRequest request,
                                   HttpServletResponse response, Integer totalPrice) {
        // 跳转到paysuccess.jsp页面，告诉用户已经成功支付了多少钱
        System.out.println("paysuccess====================");
        ModelAndView mav = new ModelAndView("paysuccess2");
        /** 将分转换为元 */
        BigDecimal b1 = new BigDecimal(totalPrice);
        BigDecimal b2 = new BigDecimal(100);

        mav.addObject("money", b1.divide(b2));
        System.out.println("paysuccess====end================");
        return mav;
    }



}
